package com.stark.commons.spring.core.boot.config;

import java.net.UnknownHostException;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.stark.commons.spring.core.support.cache.CacheService;
import com.stark.commons.spring.core.support.cache.RedisService;

/**
 * redis 自动配置。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Configuration
public class RedisAutoConfig {
	
	@Configuration
	@ConditionalOnClass(name = "org.springframework.data.redis.core.RedisOperations")
	@AutoConfigureBefore(RedisAutoConfiguration.class)
	protected static class RedisTemplateConfig {
		
		@Bean
		@ConditionalOnMissingBean(name = "redisTemplate")
		public RedisTemplate<Object, Object> redisTemplate(
				RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
			RedisTemplate<Object, Object> template = new RedisTemplate<>();
			template.setConnectionFactory(redisConnectionFactory);
			template.setKeySerializer(new StringRedisSerializer());
			template.setHashKeySerializer(new StringRedisSerializer());
			template.afterPropertiesSet();
			return template;
		}
		
	}
	
	@Configuration
	@ConditionalOnClass(name = "org.springframework.data.redis.core.RedisOperations")
	@AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration")
	protected static class RedisCacheServiceConfig {
		
		@Bean
		@ConditionalOnMissingBean(name = "cacheService")
		public CacheService cacheService(RedisCacheManager redisCacheManager) {
			return new RedisService(redisCacheManager);
		}
		
	}

}
